package com.example.onlinemusic.controller;

import com.example.onlinemusic.constant.Constant;
import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.Result;
import com.example.onlinemusic.model.User;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/test")
    public Result test(){
        return new Result();
    }

    //TODO  用户注册功能
    @RequestMapping("/register")
    public Result register(String username,String password){
        User userInfo = userMapper.userLogin(username);

        if (userInfo!=null){
            return new Result(Constant.FAIL_CODE,"用户名重复",null);
        }
        User user  = new User();
        user.setUserName(username);
        String s = bCryptPasswordEncoder.encode(password);
        user.setPassword(s);
        if(userMapper.userRegister(user)==1){
            return new Result(Constant.SUCCESS_CODE,"注册成功",user);
        }else {
            return new Result(Constant.FAIL_CODE, "注册失败", null);
        }
    }


    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpSession session) {
        //判断
        User userInfo = userMapper.userLogin(username);

        if (userInfo==null){
            log.info("数据库查无此人");
            //失败
            return new Result(Constant.FAIL_CODE,"登录失败",userInfo);
        }else {
            //成功
            if(bCryptPasswordEncoder.matches(password,userInfo.getPassword())){
                log.info("账号密码正确 user = "+userInfo.getUserName());
                //写到session里
                session.setAttribute(Constant.LOGINUSER_SESSION_KEY,userInfo);
                userInfo.setPassword("");
                return new Result(Constant.SUCCESS_CODE,"登录成功",userInfo);
            }else {
                log.info("密码错误");
                return new Result(Constant.FAIL_CODE,"登录失败",userInfo);
            }
        }

    }
}
